﻿using Kang.ExtendMethod;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using NLog;
using System;
using System.Dynamic;
using System.Diagnostics;
using Chloe;

namespace Kang.Api.Filters
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class CheckTokenFilterAttribute : Attribute, IActionFilter
    {
        Logger logger = LogManager.GetCurrentClassLogger();

        public CheckTokenFilterAttribute()
        {
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (Debugger.IsAttached)
            {
                return;
            }
            try
            {
                string token = context.HttpContext.Request.Headers["Authorization"];
                if (token.IsBlank())
                {
                    throw new Exception("未提供Token！");
                }
                // 此处编写验证token的逻辑
            }
            catch (Exception e)
            {
                logger.Error(e);
                dynamic json = new ExpandoObject();
                json.data = null;
                ContentResult result = new ContentResult();
                result.ContentType = "application/json";
                result.StatusCode = 200;

                json.code = 10086;
                json.msg = $"{e.Message}";
                result.Content = JsonConvert.SerializeObject(json);
                context.Result = result;
            }
        }
    }
}
